//
//  RadioMainController.m
//  FoodList
//
//  Created by Jason on 16/4/8.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "RadioMainController.h"
#import "RadioMainTableViewCell.h"
#import "RadioMainModel.h"
#import "RadioListViewController.h"
#import "AppDelegate.h"
#import "RadioMainData+CoreDataProperties.h"

@interface RadioMainController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *radioTableView;
@property (nonatomic, strong) NSMutableArray *modelArr;
@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic, strong) NSManagedObjectContext *context;

@end

@implementation RadioMainController

- (NSMutableArray *)modelArr {
    if (_modelArr == nil) {
        _modelArr = [NSMutableArray array];
    }
    return _modelArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    self.context = delegate.managedObjectContext;
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"RadioMainData"];
    NSMutableArray *dataArray = [[_context executeFetchRequest:request error:nil] mutableCopy];
    if (dataArray.firstObject) {
        self.modelArr = dataArray;
    }else {
        [self requsetData];
    }
    
    self.radioTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requsetData];
    }];
    
    self.radioTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
}

- (void)requsetData {
    [RequestManger requestWithURL:@"http://search.ximalaya.com/front/v1?condition=relation&core=album&device=iPhone&kw=%E7%BE%8E%E9%A3%9F&live=true&page=1&rows=20" requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *responseDic = dataDic[@"response"];
        NSArray *docsArray = responseDic[@"docs"];
        self.modelArr = [NSMutableArray array];
        for (NSDictionary *dic in docsArray) {
            RadioMainModel *model = [[RadioMainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.modelArr addObject:model];
            RadioMainData *radioData = [NSEntityDescription insertNewObjectForEntityForName:@"RadioMainData" inManagedObjectContext:_context];
            radioData.title = model.title;
            radioData.cover_path = model.cover_path;
            radioData.created_at = model.created_at;
            radioData.intro = model.intro;
            radioData.nickname = model.nickname;
            radioData.tags = model.tags;
            radioData.myId = model.myId;
            radioData.uid = model.uid;
            radioData.play = model.play;
            radioData.tracks = model.tracks;
            [_context save:nil];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.radioTableView reloadData];
            [self.radioTableView.mj_header endRefreshing];
        });
    } error:^(NSError *error) {
        NSLog(@"fail");
    }];
}

- (void)loadMoreData {
    _pageNumber += 2;
    NSString *kwStr = @"%E7%BE%8E%E9%A3%9F";
    [RequestManger requestWithURL:[NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?condition=relation&core=album&device=iPhone&kw=%@&live=true&page=%ld&rows=20", kwStr, _pageNumber] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *responseDic = dataDic[@"response"];
        NSArray *docsArray = responseDic[@"docs"];
        for (NSDictionary *dic in docsArray) {
            RadioMainModel *model = [[RadioMainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.modelArr addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.radioTableView reloadData];
            [self.radioTableView.mj_footer endRefreshing];
        });
    } error:^(NSError *error) {
        NSLog(@"fail");
    }];
}

#pragma mark - 代理方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RadioMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"radioMainCell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"RadioMainTableViewCell" owner:nil options:nil].firstObject;
    }
    cell.model = _modelArr[indexPath.row];
    self.radioTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    RadioListViewController *radioListVc = [[RadioListViewController alloc] initWithNibName:@"RadioListViewController" bundle:[NSBundle mainBundle]];
    
    radioListVc.myId = [_modelArr[indexPath.row] myId];
    radioListVc.uid = [_modelArr[indexPath.row] uid];
    radioListVc.myTitle = [_modelArr[indexPath.row] title];

    [self.navigationController pushViewController:radioListVc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return Height / 7;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
